package com.qf.smartdevice.webscoket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smartdevice.pojo.Humiture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;

import java.util.Date;
import java.util.Map;

@Component
@EnableWebSocket
public class HumitureWebsocket extends MyBaseWebsocketHandler {

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//       此处 我们保留了super 原因是因为父类中的当前方法是有实现的并且这个实现是我们需要的 所以我们直接调用 我们只需要扩展我们自己的功能即可
        super.handleTextMessage(session, message);


//        处理设备发送过来的数据
//        设备发送过来的是一个JSON

        try {
            String jsonString = message.getPayload();
            Map map = objectMapper.readValue(jsonString, Map.class);
            Double humidity = (Double) map.get("humidity");// 湿度
            Double temperature = (Double) map.get("temperature");//温度,注意此处的格式是华氏温度
            //5×(F-32)/9
            System.err.println("收到的湿度是 :====>" + humidity + "----->温度是:-==>" + temperature);
            String uuid = (String) session.getAttributes().get("uuid");
            //TODO 发送时间把上面的数据带出去 温湿度 service
            Humiture humiture = new Humiture();
            humiture.setHumidity(humidity);
            humiture.setTemperature(temperature);
            humiture.setDeviceUuid(uuid);
            humiture.setUploaddate(new Date());
            context.publishEvent(humidity);//发布事件
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }
}
